/*
 * Copyright (c) 2009-2010 HIT Microelectronic Center
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met: redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer;
 * redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution;
 * neither the name of the copyright holders nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * Authors: Jin Yinghan
 *          Gou Pengfei
 */

#ifndef __CPU_EDGE_BPRED_UNIT_HH__
#define __CPU_EDGE_BPRED_UNIT_HH__

#include <list>

#include "base/statistics.hh"
#include "base/types.hh"
#include "cpu/inst_seq.hh"
#include "cpu/edge/pred/2bit_local.hh"
#include "cpu/edge/pred/btb.hh"
#include "cpu/edge/pred/ibtb_tonb.hh"
#include "cpu/edge/pred/btb_new.hh"
#include "cpu/edge/pred/ctb.hh"
#include "cpu/edge/pred/ras.hh"
#include "cpu/edge/pred/hyst_btype.hh"
#include "cpu/edge/pred/tournament.hh"
#include "cpu/edge/pred/perceptron.hh"
#include "cpu/edge/pred/tournament_perceptron.hh"
#include "cpu/edge/pred/piecewise.hh"
#include "cpu/edge/pred/piecewise_exit.hh"
#include "cpu/edge/pred/piecewise_type.hh"
#include "cpu/edge/pred/tournament_type.hh"
#include "cpu/edge/pred/tage_type.hh"
#include "cpu/edge/pred/tage_exit.hh"
#include "cpu/edge/pred/tournament_framework.hh"
#include "cpu/edge/pred/twostage_framework.hh"
#include "cpu/edge/pred/global_type.hh"
#include "cpu/edge/pred/global_exit.hh"
#include "cpu/edge/pred/local_type.hh"
#include "cpu/edge/pred/local_exit.hh"
#include "cpu/edge/pred/tour_framework_exit.hh"
#include "cpu/edge/pred/history_tracker.hh"

class DerivEdgeCPUParams;

/**
 * Basically a wrapper class to hold both the branch predictor
 * and the BTB.
 */
template<class Impl>
class EdgeBPredUnit
{
  public:
    typedef typename Impl::DynInstPtr DynInstPtr;
    typedef typename Impl::EdgeBlockPtr BlockPtr;
    typedef TheISA::ExitID ExitID;
    typedef TheISA::BlockID BlockID;
    typedef TheISA::ExitType ExitType;	

    enum PredType {
        Unknown,
        Perf,           /// Perfect predictor
        Percep,         /// Perceptron predictor
        Tour,           /// Tournament predictor
        NewTour,        /// New tournament predictor
        TourPercep,     /// Tournament perceptron predictor
        TargetOnly,     /// Ignoring EXIT predictor, BTB only
        Hysteresis,     /// Using a simple hysteresis bit to predict
        Piecewise,      /// Piecewise predictor for exit-based, or for two-stage type-only
        PiecewiseSType,  /// Piecewise predictor for type-only, single-stage
        TAGE,            /// TAGE predictor
        Twostage,        /// Two-stage predictor
        Global,          /// Global predictor
        Local,           /// Local predictor
        PerfTypeOnly     /// Only type predicotr is perfect
    };

    enum BTBType {
        BTBUnknown,
        NormalBTB,      /// Normal BTB, deprecated!!!
        IndirectBTB,    /// BTB with histories, behaving like an indirect BTB, deprecated!!
        NewBTB          /// New BTB with alias free and various indexing mode.
    };

  private:
    PredType exitPredictor;

    PredType btypePredictor;

    BTBType btbType;

    const std::string _name;

  public:

    /**
     * @param params The params object, that has the size of the BP and BTB.
     */
    EdgeBPredUnit(DerivEdgeCPUParams *params);

    ~EdgeBPredUnit() ;

    const std::string &name() const { return _name; }

    /**
     * Registers statistics.
     */
    void regStats();

    void switchOut();

    void takeOverFrom();

    /**
     * @TODO: Add comments
     */
    ExitID predict(BlockID oldest_block_id,
                   BlockPtr &block,
                   Addr &pred_target, 
                   ExitType &exit_type,
                   int addr_space_id,
                   ThreadID tid);

    /**
     * @TODO: Add comments
     */
    void update(const BlockID done_sn,
                ThreadID tid, 
                Addr block_pc, 
                int addr_space_id,
                const Addr corr_target,
                ExitType actually_branch_type,
                ExitType pred_branch_type,
                bool seq_mispredicted,
                ExitID actually_exit_id,
                ExitID pred_exit_id,
                bool exit_mispredicted);

    /**
     * Squashes all outstanding updates until a given sequence number.
     * @param squashed_sn The sequence number to squash any younger updates up
     * until.
     * @param tid The thread id.
     */
    void squash(const BlockID squashed_sn, ThreadID tid);

    /**
     * Squashes all outstanding updates until a given sequence number, and
     * corrects that sn's update with the proper address and taken/not taken.
     */
    void squash(const BlockID squashed_sn,
                int addr_space_id,
                Addr block_pc,
	        const Addr corr_target,
                ExitType actually_branch_type,
                ExitType pred_branch_type,
                bool seq_mispredicted,
                ExitID actually_exit_id,
                ExitID pred_exit_id,
                bool exit_mispredicted,
                ThreadID tid);

    /**
     * @param bp_history Pointer to the history object.  The predictor
     * will need to update any state and delete the object.
     */
    void BPSquash(BlockID block_id,
                  Addr block_pc,
                  ExitID actually_exit_id,
                  ExitID pred_exit_id,
                  ThreadID tid);

    /**
     * Sqush all the branch type predictors.
     * */
    void BTypeSquash(BlockID squashed_sn,
                     Addr block_pc,
                     int addr_space_id, 
                     ExitID actually_exit_id,
                     ExitType actually_btype,
                     ExitType pred_btype,
                     bool seq_mispredicted,
                     ThreadID tid,
                     uint64_t predication_hist);

    void BPSquash(BlockID block_id, ThreadID tid);

    void BTypeSquash(BlockID squashed_sn, ThreadID tid);

    /**
     * Looks up a given PC in the BP to see if it is taken or not taken.
     */
    ExitID BPLookup(BlockID block_id,
                    BlockID oldest_block_id,
                    Addr block_pc, 
                    int addr_space_id,
                    ThreadID tid);

    /**
     * Looks up the branch type predictor.
     * */
    ExitType BTypeLookup(BlockPtr & block,
                         BlockID block_id,
                         BlockID oldest_block_id,
                         Addr block_pc, 
                         ExitID pred_exit_id,
                         int addr_space_id,
                         ThreadID tid, 
                         uint64_t predication_hist);

    /**
     * Updates the BP with taken/not taken information.
     */
    void BPUpdate(BlockID block_id,
                  Addr block_pc,
                  int addr_space_id, 
                  ExitID actually_exit_id,
                  ExitID pred_exit_id,
                  ThreadID tid);

    /**
     * Updates the branch type predictor.
     * */
    void BTypeUpdate(BlockID done_sn,
                     Addr block_pc,
                     int addr_space_id, 
                     ExitID actually_exit_id,
                     ExitType actually_btype,
                     ExitType pred_btype,
                     bool seq_mispredicted,
                     ThreadID tid,
                     uint64_t predication_hist);

    /**
     * Get global history from a predictor.
     * */
    uint64_t getGlobalHistory(BlockID block_id, ThreadID tid);

    /**
     * Get path history from a predictor.
     * */
    uint64_t getPathHistory(BlockID block_id, ThreadID tid);

    void dump();

  private:

    /** The tournament branch predictor. */
    TournamentBP<Impl> *tournamentBP;

    /** The new tournament branch predictor. */
    TourFrameworkExit<Impl> *newTourExitBP;

    /** The perceptron branch predictor.*/
    PerceptronBP<Impl> *perceptronBP;

    /** The tournament predictor using perceptron and local.*/
    TournamentPerceptron<Impl> *tournamentPerceptron;

    /** The piecewise exit predictor. */
    PiecewiseExitP<Impl> *piecewiseExitP;

    /** The Local exit predictor. */
    LocalExitP<Impl> *localExitBP;

    /** The Global exit predictor. */
    GlobalExitP<Impl> *globalExitBP;

    /** The TAGE exit predictor. */
    TAGEExitP<Impl> *tageExitBP;

    /** The branch type predictor using a simple hysteresis bit. */
    HysteresisTypeP<Impl> *hysteresisBtypeBP;

    /** The branch type predictor using a piecewise predictor. */
    PiecewiseBP<Impl> *piecewiseBtypeBP;

    /** The branch type predictor using a tournament predictor. */
    TournamentTypeP<Impl> *tournamentBtypeBP;

    /** The branch type predictor using the new tournament predictor. */
    TournamentFramework<Impl> *newTourBtypeBP;

    /** The branch type predictor using global type predictor only. */
    GlobalTypeP<Impl> *globalBtypeBP;

    /** The branch type predictor using local type predictor only. */
    LocalTypeP<Impl> *localBtypeBP;

    /** The branch type predictor using a TAGE predictor. */
    TAGETypeP<Impl> *tageBtypeBP;

    /** The branch type predictor using a two-stage strategy. */
    TwostageFramework<Impl> *twostageBtypeBP;

    /**
     * The branch type predictor using piecewise predictor only.
     * single stage.
     * */
    PiecewiseTypeP<Impl> *piecewiseBStypeBP;

    /**
     * A history tracker to hold all types of histories.
     * TODO : currently only global histories are supported. 
     * */
    HistoryTracker<Impl> historyTracker;
	
    /** The BTB. Deprecated. */
    DefaultBTB defaultBTB;

    /** The IBTB. Deprecated. */
    IBTB iBTB;

    /** New BTB with alias free table and various indexing mode. */
    BTB<Impl> *newBTB;

    /** The per-thread return address stack. */
    ReturnAddrStack<Impl> RAS;

    /** The  CTB. */
    DefaultCTB CTB;   

    /** The number of bits to align*/
    unsigned blockShiftAmt;

    /** Stat for number of BP lookups. */
    Stats::Scalar lookups;
    /** Stat for number of conditional branches predicted. */
    Stats::Scalar condPredicted;
    /** Stat for number of conditional branches predicted incorrectly. */
    Stats::Scalar condIncorrect;
    /** Stat for number of BTB lookups. */
    Stats::Scalar BTBLookups;
    /** Stat for number of BTB hits. */
    Stats::Scalar BTBHits;
    /** Stat for number of times the BTB is correct. */
    Stats::Scalar BTBCorrect;
    /** Stat for number of times the RAS is used to get a target. */
    Stats::Scalar usedRAS;
    /** Stat for number of times the RAS is incorrect. */
    Stats::Scalar RASIncorrect;
};

#endif // __CPU_EDGE_BPRED_UNIT_HH__
